package com.jiaai.web.member;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.auth.model.AccessToken;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.common.api.ICodeApi;
import com.jiaai.exception.ServerException;
import com.jiaai.filter.aop.TokenIntercept;
import com.jiaai.member.api.IMemberApi;
import com.jiaai.member.api.IWalletAPI;
import com.jiaai.member.model.BMember;
import com.jiaai.member.model.EditMemVO;
import com.jiaai.member.model.MemberSearch;
import com.jiaai.util.*;
import com.jiaai.util.geograph.GeoHash;
import com.jiaai.util.geograph.LocationBean;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * class_name:ZMemberController
 * describe:TODO
 * create_user:张昉平
 * create_date:2017/12/18
 * create_date:14:39
 */
@RestController
@RequestMapping("/api/v1/app")
public class MemberController {

    @Reference
    private IMemberApi iMemberApi;
    @Reference
    private ICodeApi iCodeApi;
    @Reference
    private IWalletAPI walletAPI;

    @Reference
    private ICodeApi codeApi;

    /**
     * 重置或找回密码
     * @param mobile
     * @param password
     * @return
     */
    @PostMapping("/reset")
    @TokenIntercept(checkVisitor = true)
    public Object resetPwd(@RequestParam String mobile, @RequestParam String password){
        try {
            iMemberApi.resetPwd(mobile,password);
            return RestResultGenerator.genSuccessResult("成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }
    }

    /**
     * 绑定手机号码
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/bindPhone")
    @TokenIntercept(checkVisitor = true)
    public  Object bindPhone(String phone,String code)throws ServerException{
        boolean isOk=false;
        try {
            isOk=codeApi.checkCode(phone,code);
         }catch (Exception e){
            return  RestResultGenerator.genErrorResult(e.getMessage());
        }
        if(!isOk){
            return  RestResultGenerator.genErrorResult("验证码错误");
        }
        AccessUser accessUser= RequestUtils.getUser();
        Map<String,Object> params=new HashedMap();
        params.put("mId",accessUser.getUserId());
        params.put("mobile",phone);
        iMemberApi.modifyUserData(params);
        return  RestResultGenerator.genSuccessResult("修改成功");
    }

    @PostMapping("/member/modify")
    @TokenIntercept(checkVisitor = true)
    public  Object modifyUserData(@RequestParam  Map<String,Object>  params)throws ServerException{
        AccessUser accessUser= RequestUtils.getUser();
        params.put("mId",accessUser.getUserId());
        iMemberApi.modifyUserData(params);
        return  RestResultGenerator.genSuccessResult("修改成功");
    }

    /**
     * 绑定微信
     * @param code
     * @return
     */
    @PostMapping("/save")
    @TokenIntercept(checkVisitor = true)
    public Object save( @RequestParam String code){
        AccessUser user = RequestUtils.getUser();
        JSONObject obj = WeiXinUtil.getJSON("wxbcb3914d8111c047", code, "bf1c01abe0f900c8d713c8d26db8622a");
        String accessToken = obj.getString("access_token");
        String openId = obj.getString("openid");
        String unionId = obj.getString("unionid");
        if (openId == null && unionId == null){
            return RestResultGenerator.genErrorResult("微信授权失败");
        }
        try {
            obj = WeiXinUtil.getUserInfoByOpenId(openId, accessToken);
            iMemberApi.saveWXUnionId(user.getUserId(), obj);
            return RestResultGenerator.genSuccessResult("绑定微信成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResultGenerator.genErrorResult("微信授权失败");
    }

    /**
     * 通过微信unionId登录
     * @param code
     * @return
     */
    @PostMapping("/wxlogin")
    public Object wxlogin(@RequestParam String code, Integer channelId, HttpServletRequest request)throws  ServerException{
        JSONObject obj = WeiXinUtil.getJSON("wx5c54e79bc8e124a1", code, "6390468253a6695392c2fc4353f737bf");
        String openId = obj.getString("openid");
        String unionId = obj.getString("unionid");
        if (openId == null && unionId == null){
            return RestResultGenerator.genErrorResult("微信授权失败");
        }

        //返回mId和token
        try {
            Object ob=iMemberApi.wxLogin(unionId);
            if(ob!=null){
                return  RestResultGenerator.genSuccessResult(ob);
            }
        }catch (Exception e){
            return  RestResultGenerator.genErrorResult(e.getMessage());
        }

        try {
            JSONObject userInfo= WeiXinUtil.getUserInfoByOpenId(openId,obj.getString("access_token"));
            Map<String,Object> params=new HashedMap();
            params.put("unionId",unionId);
            params.put("channelId",channelId);
            params.put("openId",openId);
            params.put("nickName",userInfo.getString("nickname"));
            params.put("sex",userInfo.getIntValue("sex"));
            params.put("avatar",userInfo.getString("headimgurl"));
            params.put("city",userInfo.getString("city"));
           return RestResultGenerator.genSuccessResult( iMemberApi.register(params));

        } catch (Exception e) {
            throw  new  ServerException("获取用户信息失败");
        }


    }


    /**
     * 通过手机方式登录
     * @return
     */
    @PostMapping("/mobile/login")
    public Object mobileLogin(@RequestParam("mobile")  String mobile, @RequestParam("code") String code)throws  ServerException{
        if(codeApi.checkCode(mobile,code)){
            Object dataMap=iMemberApi.phoneLogin(mobile);
            if(dataMap==null){
                return  RestResultGenerator.genSuccessResult("");
            }
                return  RestResultGenerator.genSuccessResult(dataMap);

        }else {
            return  RestResultGenerator.genErrorResult("验证码错误");
        }
    }
    /**
     * 检测手机是否已注册
     * @param mobile
     * @return
     */
    @GetMapping("/checkMobile")
    public Object checkMobile(@RequestParam String mobile){
        if (!iMemberApi.checkMobile(mobile)){
            return RestResultGenerator.genSuccessResult("未注册");
        }
        return RestResultGenerator.genErrorResult("已注册啦!");
    }

    //注册
    @PostMapping("/reg")
    public Object reg(@RequestParam Map<String,Object> params){
        try {
            if (!iMemberApi.checkMobile(params.get("mobile").toString())){
                params.put("sex",Integer.valueOf(params.get("sex").toString()));
                return RestResultGenerator.genSuccessResult(iMemberApi.register(params));
            }
            return RestResultGenerator.genErrorResult("该手机号码已注册啦!");
        } catch (ServerException e) {
            e.printStackTrace();
            throw new RuntimeException("注册失败");
        }
    }


    //登录
    @PostMapping("/login")
    public Object login(@RequestParam String mobile, @RequestParam String password)throws  ServerException{
        return RestResultGenerator.genSuccessResult(iMemberApi.loginPwd(mobile, password));
    }

    /**
     * 获取我的信息
     * @return
     */
    @GetMapping("/info")
    @TokenIntercept(checkVisitor = true)
    public Object getMyinfo(HttpServletRequest request){
        AccessUser user = RequestUtils.getUser();
        try {
            return RestResultGenerator.genSuccessResult(iMemberApi.findMemberInfoById(user.getUserId()));
        } catch (Exception e) {
            if (e.getMessage().equals("com.jiaai.exception.TokenException")){
                return RestResultGenerator.genErrorResult("token已失效请重新登录");
            }
            e.printStackTrace();
            throw new RuntimeException("获取失败");
        }
    }

    //同步地理位置
    @PostMapping("/locate")
    @TokenIntercept
    public Object locate(LocationBean locationBean
            , HttpServletRequest request){
        AccessUser user = RequestUtils.getUser();
        try {
            String ip = HttpClientUtil.getIpAddress(request);
            locationBean.setIpAddr(ip);
            locationBean.setGeoHash(new GeoHash(locationBean.getLat(), locationBean.getLng()).getGeoHashBase32());
            iMemberApi.udpateLocation(user.getUserId(), locationBean);
            return RestResultGenerator.genSuccessResult("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("服务器异常");
        }
    }

    //修改会员信息
    @PostMapping("/editInfo")
    @TokenIntercept(checkVisitor = true)
    public Object editInfo(@RequestBody EditMemVO memVO){
        AccessUser user = RequestUtils.getUser();
        if (memVO != null) memVO.setmId(user.getUserId());

        boolean flag = iMemberApi.editInfo(memVO);
        if (flag){
            return RestResultGenerator.genSuccessResult("操作成功");
        }
        return RestResultGenerator.genErrorResult("操作失败");
    }

    /**
     * 注销
     * @param request
     * @return
     */
    @PostMapping("/loginOut")
    @TokenIntercept
    public Object loginOut(HttpServletRequest request){
        try {
            AccessUser user = RequestUtils.getUser();
            iMemberApi.loginOut(user.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResultGenerator.genSuccessResult("ok");
    }

    /**
     * 查看对方会员信息
     * @param mId 对方的mId
     * @return
     */
    @GetMapping("/lookInfo")
    @TokenIntercept
    public Object lookInfo(@RequestParam String mId){
        AccessUser user = RequestUtils.getUser();
        return  RestResultGenerator.genSuccessResult(iMemberApi.lookMemberInfo(mId));
    }





    //获取我的余额
    @GetMapping("/myMoney")
    @TokenIntercept(checkVisitor = true)
    public Object getMyMoney(){
        AccessUser user = RequestUtils.getUser();
        try {
            return RestResultGenerator.genSuccessResult(walletAPI.findBymId(user.getUserId()));
        } catch (ServerException e) {
            e.printStackTrace();
            return RestResultGenerator.genErrorResult("获取失败");
        }
    }

    @PostMapping("/member/search/{page}")
    public  Object search(@PathVariable("page") Integer page,@RequestParam("search")String search)throws  ServerException{
        MemberSearch memberSearch=new MemberSearch();
        memberSearch.setPage(page);
        memberSearch.setSearch(search);
        return RestResultGenerator.genSuccessResult(iMemberApi.search(memberSearch));

    }
    /**
     * s会员的贡献排行
     * @param type
     * @param mId
     * @return
     * @throws ServerException
     */
    @GetMapping("/ranking/{type}")
    @TokenIntercept
    public  Object findRanking(@PathVariable("type") String type,@RequestParam("mId")String mId)throws  ServerException{
        return  RestResultGenerator.genSuccessResult(iMemberApi.findDimonsRankingByAll(type,mId));
    }



}

